package lumingweihua.future.cn.lumingweihua.home.cheyuan;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import lumingweihua.future.cn.baselibgxh.adapter.BaseViewHolder;
import lumingweihua.future.cn.baselibgxh.adapter.CommonAdapter;
import lumingweihua.future.cn.baselibgxh.base.BaseActivity;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialog;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialogEntity;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.NetworkManager;
import lumingweihua.future.cn.baselibgxh.network.PureListRequest;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.ArithmeticUtil;
import lumingweihua.future.cn.baselibgxh.utils.Constant;
import lumingweihua.future.cn.baselibgxh.utils.ImageUtils;
import lumingweihua.future.cn.lumingweihua.R;
import lumingweihua.future.cn.lumingweihua.home.domain.CarData;
import lumingweihua.future.cn.lumingweihua.home.domain.HuoyuanListData;

/**
 * Created by Administrator on 2018/3/5.
 */

public class RobOrderActivity extends BaseActivity {
    @Override
    protected void initView() {
        setContentView(R.layout.activity_rob_order);
        initTitleBar("抢单", Constant.DEFAULT_LEFT_BACK, null);
    }

    private EditText et_search;
    private CommonAdapter<CarData> adapter;
    private List<CarData> allDatas;
    private List<CarData> datas;
    private float limitNum;
    private float totalSelNum;
    @Override
    protected void initData() {
        limitNum = getIntent().getFloatExtra("limitNum",0);
        findTextView(R.id.tv_num).setHint("剩余可抢单数量"+limitNum);

        findViewById(R.id.bt_ok).setOnClickListener(this);

        datas = new ArrayList<>();
        allDatas = new ArrayList<>();
        adapter = new CommonAdapter<CarData>(context,datas,R.layout.item_rob_order_car) {

            @Override
            public void convert(BaseViewHolder holder, CarData itemData, final int position, ViewGroup parent) {
                holder.setText(R.id.tv_carnum,itemData.getCar_num());
                holder.setText(R.id.tv_sel_num,itemData.getSel_num()==0?"":(itemData.getSel_num()+""));
                holder.setImageByResource(R.id.iv_check,itemData.isSel()?R.drawable.bt_switch_on:R.drawable.bt_switch_off, ImageUtils.imgOptionsSmall);

//                addClickListener(holder.getView(R.id.bt_reduce_num),position);
//                addClickListener(holder.getView(R.id.bt_add_num),position);
                addClickListener(holder.getView(R.id.iv_check),position);
                addClickListener(holder.getView(R.id.tv_sel_num),position);
            }

            @Override
            public void processClick(int viewId, CarData itemData) {
                super.processClick(viewId, itemData);
                switch (viewId) {
                    case R.id.iv_check:
                        if(!itemData.isSel()){
                            if(totalSelNum+itemData.getSel_num()>limitNum){
                                showToast("只剩余"+limitNum+"吨可抢数量");
                                return;
                            }
                        }
                        itemData.setSel(!itemData.isSel());
                        reCalTotalSelNum();
                        setText(R.id.tv_num,totalSelNum+"");
                        adapter.notifyDataSetChanged();
                        break;
                    case R.id.bt_add_num:
                        if(itemData.isSel()){
                            if(totalSelNum+1>limitNum){
                                showToast("只剩余"+limitNum+"吨可抢数量");
                                return;
                            }
                        }
                        itemData.setSel_num(itemData.getSel_num()+1);

                        if(itemData.isSel()){
                            reCalTotalSelNum();
                            setText(R.id.tv_num,totalSelNum+"");
                        }
                        adapter.notifyDataSetChanged();

                        break;
                    case R.id.bt_reduce_num:
                        if(itemData.getSel_num()<=1){
                            return;
                        }
                        itemData.setSel_num(itemData.getSel_num()-1);

                        if(itemData.isSel()){
                            reCalTotalSelNum();
                            setText(R.id.tv_num,totalSelNum+"");
                        }
                        adapter.notifyDataSetChanged();

                        break;
                    case R.id.tv_sel_num:
                        currentCarData = itemData;
                        startActivityForResult(new Intent(context,UpdateNumActivity.class)
                                .putExtra("limitNum",limitNum-totalSelNum),102);
                        break;

                    default:
                        break;
                }
            }
        };

        ListView listview = findViewById(R.id.listview);
        listview.setAdapter(adapter);

        requestGoodsDatas();

        et_search = findViewById(R.id.et_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchGoodsDatas(et_search.getText().toString());
            }
        });
    }

    private CarData currentCarData;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 102 && resultCode == RESULT_OK){
            float num = data.getFloatExtra("num",1);
            currentCarData.setSel_num(num);

            if(currentCarData.isSel()){
                reCalTotalSelNum();
                setText(R.id.tv_num,totalSelNum+"");
            }

            adapter.notifyDataSetChanged();
        }
        if(requestCode == 68 && resultCode == RESULT_OK){
            setResult(RESULT_OK);
            finish();
        }

    }

    private void reCalTotalSelNum(){
        totalSelNum = 0;
        for(CarData cd:datas){
            if(cd.isSel()){
                totalSelNum = ArithmeticUtil.add(totalSelNum+"",cd.getSel_num()+"").floatValue();
            }
        }
    }

    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.bt_ok:
                //抢单
                String num = findTextView(R.id.tv_num).getText().toString();
                if(TextUtils.isEmpty(num) || totalSelNum == 0){
                    showToast("请选择抢单数量");
                    return;
                }

                if(totalSelNum>limitNum){
                    showToast("抢单数量不得超过"+limitNum+"吨");
                    return;
                }

                new YesOrNoDialog(context, new YesOrNoDialogEntity("确定抢单吗\n请真实填写抢单信息，提高抢单成功率", "取消", "确定"),
                        new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                            @Override
                            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                switch (yesOrNoType) {
                                    case BtnOk:
                                        requestSet();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }).show();

                break;

            default:
                break;
        }
    }

    /** 请求标识 **/
    private final int REQUEST_SET = 0;
    private final int REQUEST_DATAS = 1;
    private final int REQUEST_SEARCH = 2;
    /**
     *
     */
    private void requestSet(){
//        showProgressBar(null);
//
//        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
//                context,"",this);
//
//        req.setParam("apiCode", "_grab_indent_001");
//        req.setParam("userToken", MyApplication.getInstance().getUserToken());
//        //传这个参数代表修改，没有代表新增地址
//        req.setParam("good_num", getIntentExtra("good_num"));
//        req.setParam("grab_weight", totalSelNum+"");

        List<JsonData> jsons = new ArrayList<>();
        int num = 0;
        for(CarData cd:datas){
            if(cd.isSel()){
                num++;
                jsons.add(new JsonData(cd.getId(),cd.getSel_num()+""));
            }
        }
//        req.setParam("json", new Gson().toJson(jsons));
//        json  车辆id和车辆装载吨位数传json  例如：[{"id":"1","rough_weight":"10"},{"id":"2","rough_weight":"13"}]

        startActivityForResult(new Intent(context,DriverInfoActivity.class)
                .putExtra("good_num",getIntentExtra("good_num"))
                .putExtra("grab_weight",totalSelNum+"")
                .putExtra("json",new Gson().toJson(jsons))
                .putExtra("num",num)
                ,68);
//		//获取token
//        String token = NetworkManager.getInstance().getPostToken(req.getParam());
//        req.setParam("token", token);
//
//        addRequestQueue(req, REQUEST_SET, new ReqTag.Builder().handleSimpleRes(true));
    }

    public class JsonData{
        public String car_id;
        public String rough_weight;

        public JsonData(String car_id, String rough_weight) {
            this.car_id = car_id;
            this.rough_weight = rough_weight;
        }
    }

    protected void requestGoodsDatas() {
        // TODO Auto-generated method stub
        showProgressBar(null);
        PureListRequest<CarData, MamaHaoServerError> req = new PureListRequest<>(
                context,
                "",
                this,
                CarData.class);

        req.setParam("apiCode", "_user_car_001");
        req.setParam("onlypasscheck", "1");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_DATAS, new ReqTag.Builder().handleSimpleRes(true));

    }

    private void searchGoodsDatas(String license){

        if(TextUtils.isEmpty(license)){
            datas.clear();
            datas.addAll(allDatas);
            adapter.notifyDataSetChanged();
        }else{
            showProgressBar(null);
            PureListRequest<CarData, MamaHaoServerError> req = new PureListRequest<>(
                    context,
                    "",
                    this,
                    CarData.class);

            req.setParam("apiCode", "_search_license_001");
            req.setParam("license", license);
            req.setParam("userToken", MyApplication.getInstance().getUserToken());

            //获取token
            String token = NetworkManager.getInstance().getPostToken(req.getParam());
            req.setParam("token", token);

            addRequestQueue(req, REQUEST_SEARCH, new ReqTag.Builder().handleSimpleRes(true));
        }

    }

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        super.onResponseSuccess(tag, data);
        switch (tag.getReqId()) {
            case REQUEST_SET:
                new YesOrNoDialog(context, new YesOrNoDialogEntity("抢单信息已通过短信方式发送给货主，请耐心等待货主与您联系!", null, "我知道啦"),
                        new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                            @Override
                            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                switch (yesOrNoType) {
                                    case BtnOk:
                                        setResult(RESULT_OK);
                                        finish();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }).show();
                break;
            case REQUEST_DATAS:
                datas.addAll((List<CarData>)data);
                allDatas.addAll((List<CarData>)data);
                adapter.notifyDataSetChanged();
                break;
            case REQUEST_SEARCH:
                List<CarData> cars = (List<CarData>) data;
                List<CarData> newCars = new ArrayList<>();
                if(cars!=null && cars.size()>0){
                    for(CarData cd:cars){
                        //筛选车牌
                        for(CarData card:allDatas){
                            if(card.getId().equals(cd.getCar_id())){
                                newCars.add(card);
                                break;
                            }

                        }
                    }
                }

                datas.clear();
                datas.addAll(newCars);
                adapter.notifyDataSetChanged();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResponseFailure(ReqTag tag, MamaHaoServerError error, AbstractRequest.MamaHaoError clientError) {
        super.onResponseFailure(tag, error, clientError);
    }
}
